<template>
  <div>
    <el-container>
      <el-header>{{ flowForm.name }}</el-header>
      <el-header height="40px">
        <ul class="option_tools">
          <li>
            <el-icon><ArrowLeft /></el-icon>
            <p>上一步</p>
          </li>
          <li>
            <el-icon><ArrowRight /></el-icon>
            <p>下一步</p>
          </li>
          <li @click="previewXml()">
            <el-icon><Document /></el-icon>
            <p>获取xml</p>
          </li>
          <li @click="saveFlow()">
            <el-icon><CircleCheck /></el-icon>
            <p>保存</p>
          </li>
          <li @click="saveFlowTemplate()">
            <el-icon><CircleCheck /></el-icon>
            <p>另存模板</p>
          </li>
          <li @click="deleteShap()">
            <el-icon><Delete /></el-icon>
            <p>删除</p>
          </li>
          <li style="color: #00af00" @click="run()">
            <el-icon><VideoPlay /></el-icon>
            <p>执行</p>
          </li>
          <li style="color: rgb(73, 156, 84)">
            <el-icon><CaretRight /></el-icon>
            <p>debug</p>
          </li>
          <li @click="showResult()">
            <el-icon><View /></el-icon>
            <p>结果集</p>
          </li>
          <li @click="sysEstimate()">
            <el-icon><View /></el-icon>
            <p>浏览器配额</p>
          </li>
          <li @click="paramSetting()">
            <el-icon><Setting /></el-icon>
            <p>参数配置</p>
          </li>
          <!-- <li style="color: #e6a23c" @click="showCode">
            <SvgIcon name="ui" v-show="!codeFlag"></SvgIcon>
            <p v-show="!codeFlag">设计器</p>
            <SvgIcon name="code" v-show="codeFlag"></SvgIcon>
            <p v-show="codeFlag">XML</p>
          </li> -->
          <!-- <li style="color: #000" @click="openOption()">
            <SvgIcon name="help"></SvgIcon>
            <p>帮助</p>
          </li>
          <li style="color: #000" @click="openOption()">
            <SvgIcon name="idea"></SvgIcon>
            <p>小技巧</p>
          </li> -->
        </ul>
      </el-header>
      <el-container style="border: 1px solid rgba(0, 0, 0, 0.08); height: calc(100vh - 170px); border-radius: 4px">
        <el-aside width="180px" style="height: 100%; overflow-y: auto">
          <el-collapse v-model="activeTool">
            <el-collapse-item :name="components.code" v-for="components in componentList" :key="components.code">
              <template #title>
                <span style="margin: 0 10px" class="collapse-item_title">{{ components.title }}</span>
              </template>
              <ul class="tools">
                <li v-for="item in components.toolbarItems" :key="item['title']" ref="toolItemRef" :data-item="JSON.stringify(item)" class="tool_item">
                  <img :src="item['icon']" :alt="item['title']" />
                  <span>{{ item["title"] }}</span>
                </li>
              </ul>
            </el-collapse-item>
          </el-collapse>
        </el-aside>
        <el-main style="height: 100%; overflow: hidden; background-color: #f6fbff"><div class="example-editor" ref="editorRef" style="height: 100%; overflow: auto"></div> </el-main>
      </el-container>
    </el-container>
    <setting ref="settingRef" @update="updateCell" />
    <RunResult ref="runResultRef" />
    <LocalParams ref="localParamsRef" @update="updateLocalParams" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, onActivated, ref, Ref, onDeactivated } from "vue";
import { SpiderEditor } from "./myMxGraph/spider-editor";
import { componentList } from "./myMxGraph/toolbar";

import baseService from "@/service/baseService";
import setting from "./setting.vue";
import RunResult from "./run-result.vue";
import LocalParams from "./local-params.vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import bus from "@/utils/bus";
const route = useRoute();
const router = useRouter();
import "@maxgraph/core/css/common.css";
// const componentList: Ref<Component[]> = ref([]);
const activeTool = ref();
const editorRef: Ref<HTMLDivElement | undefined> = ref();
const toolItemRef: Ref<HTMLDivElement | undefined> = ref();
const currentGraph: Ref<SpiderEditor | undefined> = ref();
const settingRef = ref();
const settingNode = (item: any) => {
  settingRef.value.init(item);
};
const previewXml = () => {
  if (currentGraph.value) {
    console.log(currentGraph.value.getXml());
  }
};

const localParamsRef = ref();
const paramSetting = () => {
  localParamsRef.value.init(flowForm.value.params);
};
const updateLocalParams = (params: string) => {
  flowForm.value.params = params;
};

const runResultRef = ref();
const showResult = () => {
  runResultRef.value.show();
};
const run = () => {
  if (currentGraph.value) {
    const xmlCode = currentGraph.value.getXml();
    runResultRef.value.run(xmlCode, flowForm.value.params);
  }
};
const createGraph = (container: HTMLElement) => {
  const graph = new SpiderEditor({
    element: container,
    // 选中节点后打开属性面板
    selectedCellListener: (cell: any) => {
      loadTemplate(cell);
    }
  });
  currentGraph.value = graph;
  // 加载图形
  graph.initToolbar(toolItemRef.value);
};

const deleteShap = () => {
  if (currentGraph.value) {
    currentGraph.value.deleteSelectCells();
  }
};
// const activeCell: any = ref();
const loadTemplate = (cell: any) => {
  if (cell) {
    // activeCell.value = cell;
    const cellJson = cell.data;
    const activeCellJson = JSON.parse(JSON.stringify(cellJson));
    settingNode(activeCellJson);
  }
};

const updateCell = (cellData: any) => {
  if (Object.prototype.hasOwnProperty.call(cellData, "spiderName")) {
    flowForm.value.name = cellData.spiderName;
  }
  if (currentGraph.value) {
    currentGraph.value.updateCellProperty(cellData);
  }
};
const getXml = (id: string) => {
  // baseService
  //   .get("/spider/xml", {
  //     id: id
  //   })
  //   .then((res: any) => {
  //     if (res.code === 0) {
  //       // analysisData.value = res.data;
  //       if (currentGraph.value) {
  //         currentGraph.value.setXML(res.data);
  //         currentGraph.value.initToolbar(toolItemRef.value);
  //       }
  //     }
  //   });
};

const flowForm = ref({
  id: "",
  name: "未定义名称",
  xml: "",
  params: ""
});
const getFlowById = (id: string) => {
  baseService
    .get("/spider/get", {
      id: id
    })
    .then((res: any) => {
      if (res.code === 0) {
        flowForm.value = res.data;
        if (currentGraph.value) {
          currentGraph.value.setXml(res.data.xml);
          // currentGraph.value.initToolbar(toolItemRef.value);
        }
      }
    });
};

const saveFlowTemplate = () => {
  console.log(111);
};
const saveFlow = () => {
  if (currentGraph.value) {
    const xmlCode = currentGraph.value.getXml();
    flowForm.value.xml = xmlCode;
  }

  baseService
    .post("/spider/save", flowForm.value)
    .then((res) => {
      if (res.code === 0) {
        flowForm.value.id = res.data;
        // this.$message.success('保存成功！')
        ElMessage.success({
          message: "成功",
          duration: 1000
        });
        // bus.emit("getFlowDataListBus");

        window.localStorage.setItem("sendMessage", flowForm.value.name);
        router.replace({
          path: `/processing/edit`,
          query: {
            flowId: res.data,
            pop: "true"
          }
        });
      }
    })
    .catch((error) => {
      // this.$log.error('flowForm：' + error)
    });
};
const sysEstimate = () => {
  navigator.storage.estimate().then((estimate: any) => {
    console.log(`estimate: ${JSON.stringify(estimate)}`);
    console.log(`配额: ${Number(estimate.quota) / 1024 / 1024 / 1024}`);

    console.log(`Usage: ${estimate.usage}`);
    navigator.storage.estimate().then(function (estimate) {
      console.log(((Number(estimate.usage) / Number(estimate.quota)) * 100).toFixed(2));
    });
    // console.log(`Usage details: `, estimate.usageDetails);
  });
};
onMounted(() => {
  if (editorRef.value) {
    const container = editorRef.value;
    createGraph(container);
    if (route.query && route.query.flowId) {
      getFlowById(route.query.flowId as string);
      // getXml(route.query.flowId as string);
    }
  }
});
onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
  console.log("onDeactivated");
});
</script>

<style scoped lang="scss">
.example-editor {
  background: url("@/assets/editor/images/grid.gif");
}
.option_tools {
  margin: 0;
  padding: 0;
  list-style: none;
  li {
    list-style-type: none;
    display: inline-block;
    // border-left: 1px solid #ccc;
    margin: 0px;
    padding: 0px 12px;
    text-align: center;
    cursor: pointer;
    p {
      margin: 0;
      font-size: 12px;
    }
  }
}
.tools {
  margin: 0;
  padding: 0px 12px;
}
.collapse-item_title {
  -moz-user-select: none; /* Firefox私有属性 */
  -webkit-user-select: none; /* WebKit内核私有属性 */
  -ms-user-select: none; /* IE私有属性(IE10及以后) */
  -khtml-user-select: none; /* KHTML内核私有属性 */
  -o-user-select: none; /* Opera私有属性 */
  user-select: none; /* CSS3属性 */
}
.tool_item {
  cursor: move;
  list-style-type: none;
  margin: 4px 0;
  // width: 30px;
  height: 24px;
  line-height: 24px;
  -moz-user-select: none; /* Firefox私有属性 */
  -webkit-user-select: none; /* WebKit内核私有属性 */
  -ms-user-select: none; /* IE私有属性(IE10及以后) */
  -khtml-user-select: none; /* KHTML内核私有属性 */
  -o-user-select: none; /* Opera私有属性 */
  user-select: none; /* CSS3属性 */
  img {
    height: 16px;
    // width: 100%;
    vertical-align: middle;
  }
  span {
    margin: 0 10px;
    vertical-align: middle;
    height: 24px;
    line-height: 24px;
  }
}
</style>
